/**
 * 数据集document
 * 
 * {
 *   name: '数据源名称',
 *   datas: '?'数据集
 * }
 * 
 * @author xiufu.wang
 */

const DataSource = require('nedb')
const path = require('path')
const { createResonseError, createResonseSuccess } = require('./util')

const db = new DataSource({ filename: path.resolve(__dirname, '../../code-gen-dataset-db.db') });
db.loadDatabase()

exports.find = function (req, res) {
    db.find({}, function (err, docs) {
        res.json(createResonseSuccess(null, docs))
    })
}

exports.save = function (req, res) {
    const { data } = req.body || {}
    if (!data) {
        res.json(createResonseError('保存失败! 接口参数错误', data))
        return
    }

    //修改
    if (data._id) {
        db.update({ _id: data._id }, data, {}, function (err, numReplaced) {
            if (err) {
                res.json(createResonseError('更新数据源失败!' + err.message, numReplaced))
            } else {
                res.json(createResonseSuccess('更新成功!', numReplaced))
            }
        })
    } else {
        // 新增
        db.insert({
            name: data.name,
            datas: data.datas
        }, function (err, newDocs) {
            if (err) {
                res.json(createResonseError('添加数据源失败!' + err.message, data))
            } else {
                res.json(createResonseSuccess('添加成功!', newDocs))
            }
        });
    }
}

exports.remove = function (req, res) {
    const { data } = req.body || {}
    if (!data || !data._ids) {
        res.json(createResonseError('删除失败! 接口参数错误', data))
        return
    }
    const _ids = Array.isArray(data._ids) ? data._ids : [data._ids]
    db.remove({ _id: { $in: _ids } }, { multi: true }, function (err, numRemoved) {
        if (err) {
            res.json(createResonseError('删除数据源失败!' + err.message, numRemoved))
        } else {
            res.json(createResonseSuccess('删除数据源成功!', numRemoved))
        }
    })
}

exports.baseRouterUrl = '/mock/api/code-gen/data-set/'